package com.infonova.product.jtf.blame.callgraph;

import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.EmptyVisitor;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.MethodGen;

import com.infonova.product.jtf.blame.dto.CallGraph;

public class ClassMethodVisitor extends EmptyVisitor {

    private JavaClass clazz;
    private ConstantPoolGen constants;
    private String methodToInspect;
    private CallGraph listener;
    private int level;

    public ClassMethodVisitor(int level, JavaClass clazz, String methodToInspect, CallGraph listener) {
        this.clazz = clazz;
        this.constants = new ConstantPoolGen(clazz.getConstantPool());
        this.methodToInspect = methodToInspect;
        this.listener = listener;
        this.level = level;
    }

    public void visitJavaClass(JavaClass jc) {
        jc.getConstantPool().accept(this);
        for (Method method : jc.getMethods()) {
            if (method.getName().equals(methodToInspect)) {
                method.accept(this);
                break;
            }
        }
    }

    public void visitConstantPool(ConstantPool constantPool) {
        for (int i = 0; i < constantPool.getLength(); i++) {
            Constant constant = constantPool.getConstant(i);
            if (constant == null) {
                continue;
            }
            if (constant.getTag() == 7) {
                String referencedClass = constantPool.constantToString(constant);
            }
        }
    }

    public void visitMethod(Method method) {
        MethodGen mg = new MethodGen(method, clazz.getClassName(), constants);
        MethodVisitor visitor = new MethodVisitor(level, mg, clazz, listener);
        visitor.start();
    }

    public void start() {
        visitJavaClass(clazz);
    }
}
